import React, { useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../../types/store";
import {
  changeShow,
  editTodo,
} from "../../../store/actions/todoList";
import formatDateTime from "../../../utils/formatDateTime";
import "./index.css";
export default function Disp() {
  const { active, isEdit } = useSelector((state: RootState) => state.todoList);
  const dispatch = useDispatch();
  const area = useRef<HTMLTextAreaElement>(null);
  const changeCheck = () => {
    const item = active;
    item.complete = !item.complete;
    dispatch(editTodo({ ...item, complete: item.complete }));
  };
  const submit = () => {
    dispatch(editTodo({...active,content:area.current?.value!}))
    dispatch(changeShow(false))
  };
  return (
    <div className="disp">
      {isEdit ? (
        <>
          <header>编辑事件</header>
          <div className="Edit">
            <div className="edit-time">
                <span>时间</span>
                <span>{formatDateTime(active.time)}</span>
            </div>
            <div className="edit-content">
              <span>内容</span>
              <textarea
                cols={30}
                rows={3}
                ref={area}
                defaultValue={active.content}
              />
            </div>
            <div className="edit-state">
              <span>状态</span>
              <input
                type="checkbox"
                checked={active.complete ? true : false}
                onChange={changeCheck}
              />
            </div>
          </div>
          <div className="disp-buttons">
            <button
              onClick={() => {
                dispatch(changeShow(false));
              }}
            >
              取消
            </button>
            <button onClick={submit}>确定</button>
          </div>
        </>
      ) : (
        <>
          <header>查看事件</header>
          <div className="disp-content">
            <p>时间:&nbsp;{formatDateTime(active.time)}</p>
            <p>内容:&nbsp;{active.content}</p>
            <p>状态:&nbsp;{active.complete ? "完成" : "未完成"}</p>
          </div>
          <button
            onClick={() => {
              dispatch(changeShow(false));
            }}
          >
            确定
          </button>
        </>
      )}
    </div>
  );
}
